'use strict';


const axios = require('axios')
const urlJoin = require('url-join')
const semver = require('semver')

function getNpmInfo(npmName, registry) {
    // TODO
    if (!npmName) { return }
    const registryUrl = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl, npmName)
    return axios.get(npmInfoUrl).then(res => {
        if (res.status === 200) {
            return res.data
        }
    }).catch(err => {
        return Promis.reject(err)
    })
}

function getSemverVersion (baseVersion, versions) {
    return versions
        .filter(version => semver.gt(version, baseVersion))
        .sort((a, b) => semver.gt(a, b))
}

async function getNpmSemverVersion (baseVersion, npmName, registry) {
    const versions = await getNpmVersions(npmName, registry)
    const newVersion = getSemverVersion(baseVersion, versions)
    if (newVersion && newVersion.length) {
        return newVersion[0]
    }
}

async function getNpmVersions (npmName, registry) {
    const data = await getNpmInfo(npmName, registry)
    if (data) {
        return Object.keys(data.versions)
    } else {
        return []
    }
}

function getDefaultRegistry (isOriginnal = false) {
    return isOriginnal ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion,
};
